package TimeToWork.Android;

import android.os.Parcel;
import android.os.Parcelable;

import java.text.DecimalFormat;

public class TimePeriodLength implements Parcelable {

    public static enum TimeFormat {HMS, HM, M};

	/* Period length in [ms] */
	private long value;

	public TimePeriodLength() {
	    this.value = 0;
	}
	
	public TimePeriodLength(long length) {
		this.value = length;
	}
	
	public TimePeriodLength(Parcel in) {
	    this.value = in.readLong();
	}
	
    public void writeToParcel(Parcel out, int flags) {
        out.writeLong(this.value);
    }

    public int describeContents() {
        return 0;
    }

    public static final Parcelable.Creator<TimePeriodLength> CREATOR = new Parcelable.Creator<TimePeriodLength>() {
        public TimePeriodLength createFromParcel(Parcel in) {
            return new TimePeriodLength(in);
        }

        public TimePeriodLength[] newArray(int size) {
            return new TimePeriodLength[size];
        }
    };

	public void setLength(long length) {
	    this.value = length;
	}
	
	public long getvalue() {
		return this.value;
	}

	public String toString(TimeFormat format) {
		DecimalFormat formatter1Digit = new DecimalFormat("0");
		DecimalFormat formatter2Digit = new DecimalFormat("00");
		long seconds = (this.value + 500) / 1000;
		
		String ret = (Math.signum(seconds) < 0 ? "-" : "");
		seconds = Math.abs(seconds);
		
		switch (format) {
		case M:
			ret += formatter1Digit.format(seconds / 60);
			break;
		case HM:
		    // For correct rounding
		    seconds += 30;
			ret += formatter2Digit.format(seconds / 3600) + ":"
					+ formatter2Digit.format(seconds / 60 % 60) ;
			break;
		case HMS:
		default:
			ret += formatter2Digit.format(seconds / 3600) + ":"
					+ formatter2Digit.format(seconds / 60 % 60) + ":"
					+ formatter2Digit.format(seconds % 60);

		}

		return ret;
	}
	
	public void addTime(TimePeriodLength length) {
		this.value += length.getvalue();
	}
	
	public void subTime(TimePeriodLength length) {
		this.value -= length.getvalue();
	}
	
	public void addTime(long length) {
	    this.value += length;
	}
	
	public void subTime(long length) {
	    this.value -= length;
	}

}
